<template>
  <div class="xtx-infinite-loading" ref="container">
    <div class="loading" v-if="loading">
      <span class="img"></span>
      <span class="text">正在加载...</span>
    </div>
    <div class="none" v-if="finished">
      <span class="img"></span>
      <span class="text">亲，没有更多了</span>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'XtxInfiniteLoading'
}
</script>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

// 参数
const props = defineProps({
    loading: {
      type: Boolean,
      default: false
    },
    finished: {
      type: Boolean,
      default: false
    }
})
// 触发方法
const emit = defineEmits(['infinite'])
const container = ref(null)
// 用来判断是否在视区中
let currIsIntersecting = false
useIntersectionObserver(
    container,
    ([{ isIntersecting }], dom) => {
        currIsIntersecting = isIntersecting
        if (isIntersecting && props.loading === false && props.finished === false) {
            emit('infinite')
        }
    }, { threshold: 0 }
)
// 当finished参数改变时，需要重新判断并触发方法
watch([() => props.finished,() => props.loading], ([newFinished, newLoading]) => {
  if (newFinished) return
  if (newLoading) return
  if(currIsIntersecting) {
    emit('infinite')
  }
})
</script>

<style scoped lang='less'>
.xtx-infinite-loading {
  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 50px;
      height: 50px;
      background: url(../../assets/images/load.gif) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
  .none {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 200px;
      height: 134px;
      background: url(../../assets/images/none.png) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
}
</style>